package net.onceface.web.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import net.onceface.application.commons.InvokeResult;
import net.onceface.core.domain.Order;
import net.onceface.core.domain.enums.OrderStatus;
import net.onceface.infra.json.JsonUtil;
import net.onceface.web.utils.payment.PayToBank;

import org.apache.log4j.Logger;

/**
 * 在线支付资源类
 * **/
@Path("/payOnLine")
public class PayOnLineResources {

	Logger logger  = Logger.getLogger(PayOnLineResources.class);
	
	/**
	 * 银联跳转网关支付
	 * **/
	@SuppressWarnings("unused")
	@POST
	@Path("/ACPBank")
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_JSON})
	@Produces(MediaType.APPLICATION_JSON)
	public String ACPBank(@FormParam("orderNumber")String orderNumber){
		if(orderNumber == null){
			return JsonUtil.objectToJson(InvokeResult.failure("没有输入订单号!"));
		}
		Order order = Order.getOrderByOrderNumber(orderNumber);
		logger.info(order.getOrderNumber() + " 请求银联支付!");
		if(order != null){
			if(order.getOrderStatus() == OrderStatus.A){
				int price = (int)order.getPrice() * 100;
				String txnAmt = String.valueOf(price);
				return PayToBank.sendACPRequest(orderNumber, txnAmt);
			}else{
				logger.info("订单无需支付，订单编号 -->" + order.getOrderNumber());
				return JsonUtil.objectToJson(InvokeResult.failure("订单无需支付!"));
			}
		}
		logger.info("没找到订单，订单编号 -->" + orderNumber);
		return JsonUtil.objectToJson(InvokeResult.failure("没找到订单!"));

	}
	
	/**
	 * 银联跳转网关支付后台通知
	 * @throws UnsupportedEncodingException 
	 * *//*
	@POST
	@Path("/ACPBackResponse")
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_JSON})
	@Produces(MediaType.TEXT_PLAIN)
	public void ACPBackResponse(@Context HttpServletRequest req, 
								@Context HttpServletResponse response)throws ServletException,IOException{
		
		LogUtil.writeLog("BackRcvResponse接收后台通知开始");
		logger.info("BackRcvResponse接收后台通知开始!");
		req.setCharacterEncoding("ISO-8859-1");
		String encoding = req.getParameter(SDKConstants.param_encoding);
		logger.info("编码->" + encoding);
		// 获取银联通知服务器发送的后台通知参数
		Map<String, String> reqParam = getAllRequestParam(req);
		LogUtil.printRequestLog(reqParam);
		if(reqParam == null){
			logger.warn("后台通知参数是空的！");
		}
		Map<String, String> valideData = null;
		if (null != reqParam && !reqParam.isEmpty()) {
			Iterator<Entry<String, String>> it = reqParam.entrySet().iterator();
			valideData = new HashMap<String, String>(reqParam.size());
			while (it.hasNext()) {
				Entry<String, String> e = it.next();
				String key = (String) e.getKey();
				String value = (String) e.getValue();
				value = new String(value.getBytes("ISO-8859-1"), encoding);
				valideData.put(key, value);
			}
		}
		//重要！验证签名前不要修改reqParam中的键值对的内容，否则会验签不过
		if (!AcpService.validate(valideData, encoding)) {
			LogUtil.writeLog("验证签名结果[失败].");
			logger.info("验证签名结果[失败]!");
			//验签失败，需解决验签问题
		} else {
			LogUtil.writeLog("验证签名结果[成功].");
			logger.info("验证签名结果[成功]!");
			//【注：为了安全验签成功才应该写商户的成功处理逻辑】交易成功，更新商户订单状态
			//获取后台通知的数据，其他字段也可用类似方式获取		
			String orderId =valideData.get("orderId");
			orderApplication.editStatus(null, orderId, OrderStatus.B);
			//获取应答码，收到后台通知了respCode的值一般是00，可以不需要根据这个应答码判断。
			String respCode =valideData.get("respCode");
		}
		LogUtil.writeLog("BackRcvResponse接收后台通知结束");
		//返回给银联服务器http 200  状态码
		response.getWriter().print("ok");
	}
	
	*//**
	 * 获取请求参数中所有的信息
	 * 
	 * @param request
	 * @return
	 *//*
	public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
		Map<String, String> res = new HashMap<String, String>();
		Enumeration<?> temp = request.getParameterNames();
		if (null != temp) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				res.put(en, value);
				//在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
				System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
				if (null == res.get(en) || "".equals(res.get(en))) {
					res.remove(en);
				}
			}
		}
		return res;
	}*/
}
